<template>
    <div class="app-container">
            <!--  这里的模糊查询是根据昵称进行模糊查询的  -->
            <el-form :model="queryParams" ref="form" :inline="true">
                <el-form-item label="用户名称" class="item" prop="username" >
                    <el-input v-model="queryParams.username" placeholder="请输入用户名称"  clearable style="width: 240px" @keyup.enter.native="load" />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="Search"  @click="load">搜索</el-button>
                    <el-button icon="refresh" @click="reset">重置</el-button>
                </el-form-item>
            </el-form>
            <!--按钮区域    -->
            <div style="margin:5px">
                <el-button type="primary" plain icon="plus" @click="handleAdd">新增</el-button>
                <el-button type="success" plain icon="edit"  :disabled="single" @click="handleUpdate" >修改</el-button>
            </div>
            <!-- 列表区-->
            <el-table :data="tableData"  :header-cell-style="{background:'#eef1f6',color:'#606266'}" @selection-change="handleSelectionChange" style="width: 100%">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="userId" sortable label="ID"></el-table-column>
                <el-table-column prop="username" label="姓名"></el-table-column>
                <el-table-column prop="nickName" label="昵称"></el-table-column>
                <el-table-column prop="sex" label="性别">
                    <template #default="scope">
                        <span v-if="scope.row.sex === '1'">男</span>
                        <span v-if="scope.row.sex === '0'">女</span>
                    </template>
                </el-table-column>
                <el-table-column prop="age" label="年龄"></el-table-column>

                <el-table-column prop="phone" width="180" label="电话"></el-table-column>
                <el-table-column prop="createTime" width="180" label="创建时间"></el-table-column>
                <el-table-column fixed="right" label="操作"  width="260">
                    <template #default="scope">
                        <!--v-if="scope.row.userId !== 1"-->
                        <div >
                        <el-button type="text" icon="edit" @click="handleUpdate(scope.row)">修改</el-button>
                        <!-- 自带提示框的删除按钮 -->
                        <el-popconfirm title="确定删除吗？" @confirm="del(scope.row)">
                            <template #reference>
                                <el-button size="small" icon="delete" type="text" >删除</el-button>   <!-- 注意此处如果方法加在删除按钮上，那么在弹出提示框点击确定的时候就无法执行删除操作了，所以这里需要将删除的方法，挂到弹框的确定按钮上 -->
                            </template>
                        </el-popconfirm>
                        <el-button type="text" icon="check" @click="handleAuthRole(scope.row)">分配角色</el-button>
                        </div>
                    </template>

                </el-table-column>
            </el-table>
            <!--列表分页-->
            <div style="margin: 10px 0">
                <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-sizes="[5, 10, 15, 20]"
                        :page-size="pageSize"
                        layout="total, sizes, prev, pager, next, jumper"
                        :total="total"> //双引号里面的total是定义一个变量，在这里定义了，就需要在下面data里面初始化一下
                </el-pagination>
            </div>
        <!-- 新增用户弹窗 -->
        <el-dialog :title="title" v-model="dialogVisible" width="600px">
            <el-form :model="form" label-width="100px">
                <el-form-item label="姓名" class="item">
                    <el-input v-model="form.username" style="width:80%" ></el-input>
                </el-form-item>

                <el-form-item label="昵称" class="item">
                    <el-input v-model="form.nickName" style="width:80%" ></el-input>
                </el-form-item>

                <el-form-item label="年龄" class="item">
                    <el-input v-model="form.age" style="width:80%" ></el-input>
                </el-form-item>

                <el-form-item label="电话" class="item">
                    <el-input v-model="form.phone"  style="width:80%"></el-input>
                </el-form-item>

                <el-form-item label="性别" class="item">
                    <el-radio v-model="form.sex" label="1">男</el-radio>
                    <el-radio v-model="form.sex" label="0">女</el-radio>
                </el-form-item>

                <el-form-item label="角色" class="item">
                    <el-checkbox-group v-model="form.roleIds">
                        <el-checkbox    v-for="item in roleOptions" :label="item.roleId" :key="item.roleId">{{item.roleName}}</el-checkbox>
                    </el-checkbox-group>
                </el-form-item>

            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm">确 定</el-button>
              </span>
            </template>
        </el-dialog>
    </div>
</template>

<script>
    import request from "@/utils/request";
    import { ElMessage } from 'element-plus'
    import {listUser, updateUser,getUser,addUser,delUser } from "@/api/system/user";

    export default {
        name: 'user',
        components: {},
        data() {
            return {
                title: '',
                dialogVisible: false,
                total: 0,  //默认10条
                tableData: [],
                single:true,
                currentPage:1,
                pageSize:5,
                // 查询参数
                queryParams: {},
                form:{},
                roleOptions:[],
                item: {},
            }
        },

        //页面加载完立即执行的方法
        mounted() {
            this.load()
        },

        methods: {
            //查询方法

            load() {
                const query={
                    pageNum: this.currentPage,
                    pageSize: this.pageSize,
                    username: this.queryParams.username
                }
                 listUser(query).then(res => {
                        this.tableData = res.data.list
                        this.total = res.data.total
                })
            },

            //打开新增的弹窗
            handleAdd(){
                this.title='新增用户';
                //清空表单中的数据
                this.form={};
                //查询所有的角色信息
                getUser().then(res =>{
                    this.roleOptions=res.data;
                })
               this.dialogVisible=true;
            },

            //打开修改弹窗(和新增用的一个)
            handleUpdate(row){
                this.title='修改用户';
                const userId = row.userId || this.ids;
                this.dialogVisible=true;
                getUser(userId).then(res =>{
                    this.roleOptions=res.data.roles;  //所有角色信息
                    this.form=res.data.user;
                    this.form.roleIds=res.data.roleIds;  //该用户关联的角色
                })
            },

            //进行保存 使用aios进行数据交互
            submitForm() {
                this.$refs["form"].validate(valid =>{
                    if(valid){
                        if (this.form.userId){
                            updateUser(this.form).then(res =>{
                                ElMessage.success('修改成功');
                                this.load();  //更新完成后，重新刷新表格数据
                                this.dialogVisible = false;    //最后关闭弹窗
                            })
                        }else{
                            addUser(this.form).then(res => {
                                ElMessage.success('保存成功');
                                this.load();  //重新刷新表格数据
                                this.dialogVisible = false;    //最后关闭弹窗
                            })
                        }
                    }
                })
            },

            del(row){
                const userIds = row.userId || this.ids;
                delUser(userIds).then(res=>{
                   ElMessage.success(res.msg);
                    this.load()
                }).catch(()=>{})
            },


            //分配角色
            handleAuthRole(row){
                const userId = row.userId
                this.item.path='/authrole/'+ userId
                this.item.menuCode="authrole",
                this.item.menuName="分配角色",
                this.$router.push({ name:'authrole', params:{userId:userId}})
                this.$store.commit('selectMenu', this.item)
            },


            reset(){
                this.$resetForm('form');
            },

            //在上面的data中，pageSize和currentPaage都有默认值，这里要触发分页，需要重新根据变量赋值
            //改变当前每页条数触发
            handleSizeChange(pageSize) {
                this.pageSize = pageSize
                this.load()
            },

            //改变当前页码触发
            handleCurrentChange(pageNum) {
                this.currentPage = pageNum
                this.load()
            },

            // 多选框选中数据
            handleSelectionChange(selection) {
                this.ids = selection.map(item => item.userId)
                this.single = selection.length!=1
            },


        }
    }
</script>

<style scoped>

</style>
